package com.lj.common_web.config;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.lj.common_web.utils.ServletUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

import static com.lj.common_web.constant.CommonConstant.TRANCE_ID;

/**
 * @author luojing
 * @since 2025/4/11 14:35
 * TranceId的过滤器,用于追踪异常
 */
@Component
@WebFilter(urlPatterns = "/**", filterName = "tranceFilter")
public class TranceFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            String tranceId = ServletUtil.getParamFromRequest(request, TRANCE_ID);
            if (StrUtil.isBlank(tranceId)) {
                tranceId = IdUtil.fastSimpleUUID();
            }
            // 设置到响应头中去,前端可以用于追踪排查
            response.setHeader(TRANCE_ID, tranceId);
            // 让日志能够获取到tranceId
            MDC.put(TRANCE_ID, tranceId);
            filterChain.doFilter(request, response);
        } finally {
            MDC.remove(TRANCE_ID);
        }
    }
}
